<template>
  <div class="app-container">
    <div class="head">
      <div style="width: 260px">
        <el-date-picker
          v-model="ruleForm.date"
          type="monthrange"
          range-separator="至"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          format="YYYY-MM"
          value-format="YYYY-MM"
        />
      </div>
      <div style="display: flex">
        <div class="btn-item">
          <el-button type="primary" @click="getData">
            <el-icon style="margin-right: 6px"><Search /></el-icon>查询
          </el-button>
        </div>
        <div class="btn-item">
          <el-upload
            ref="uploadRef"
            accept=".xlsx"
            class="upload-demo"
            :limit="1"
            :http-request="uploadFile"
            :before-upload="beforeUpload"
            v-model:file-list="fileList"
          >
            <template #trigger>
              <el-button type="primary" icon="Upload">导入</el-button>
            </template>
          </el-upload>
        </div>
        <div class="btn-item">
          <el-button type="primary" @click="exportExcelBtn">
            <el-icon style="margin-right: 6px"><Download /></el-icon>导出数据
          </el-button>
        </div>
      </div>
    </div>
    <div class="tab">
      <div class="z-tab">
        <el-table class="table" style="width: 100%" :data="data" border v-loading="loading">
          <template v-for="(item, index) in column" :key="index">
            <el-table-column
              :label="item.label"
              :prop="item.name"
              :width="item.width"
              align="center"
            >
              <template #default="scope">
                <div v-if="item.itemIf">
                  {{ numberFormat(scope.row[item.name]) }}
                </div>
                <div v-if="item.type === 'date'"> {{ scope.row.time1 }}{{ scope.row.time2 }} </div>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div class="foot">
        <el-pagination
          v-model:currentPage="pageInfo.pageNum"
          :page-size="pageInfo.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[15, 30, 45, 60, 75, 90, 105]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, onMounted } from 'vue'
  import { numberFormat } from '@/utils/numberFormat.ts'
  import {
    postSiteDetailExportPageLike,
    postSiteDetailExportQueryLike,
    postSiteDetailInputExcel,
  } from '@/api/controller/site-detail-controller/index'
  import { getDashboardTime } from '@/api/controller/charging-controller/index'
  import { ElMessage } from 'element-plus'
  const loading = ref(true)

  const column = [
    { type: 'date', label: '日期', width: 140 },
    { name: 'communityName', label: '小区名' },
    { name: 'siteName', label: '站点名' },
    { name: 'profitOut', label: '分出利润(元)', width: 140, itemIf: true },
    { name: 'electricityFee', label: '电费扣除(元)', width: 130, itemIf: true },
    { name: 'outMoney', label: '实际分出的利润(元)', width: 180, itemIf: true },
    { name: 'chargeInfo', label: '负责人信息', width: 130 },
  ]
  const data = ref(null)
  const ruleForm = ref({
    date: null,
  })
  const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
  })
  const total = ref(0)
  //重置
  const reset = async () => {
    pageInfo.value = {
      pageNum: 1,
      pageSize: 15,
    }
    getData()
  }
  //初始化
  onMounted(async () => {
    let res = await getDashboardTime()
    if (res.data.month === 1) {
      ruleForm.value.date = [`${res.data.year - 1}-12`, `${res.data.year}-01`]
    } else if (res.data.month < 10) {
      ruleForm.value.date = [
        `${res.data.year}-0${res.data.month - 1}`,
        `${res.data.year}-0${res.data.month}`,
      ]
    } else {
      ruleForm.value.date = [
        `${res.data.year}-${res.data.month - 1}`,
        `${res.data.year}-${res.data.month}`,
      ]
    }
    pageInfo.value = {
      pageNum: 1,
      pageSize: 15,
    }
    getData()
  })
  const getData = async () => {
    try {
      loading.value = true
      data.value = []
      let a = {
        startYear: ruleForm.value.date[0].split('-')[0] * 1,
        endYear: ruleForm.value.date[1].split('-')[0] * 1,
        startMonth: ruleForm.value.date[0].split('-')[1] * 1,
        endMonth: ruleForm.value.date[1].split('-')[1] * 1,
      }
      const result = await postSiteDetailExportPageLike({
        ...pageInfo.value,
        ...a,
      })
      data.value = result.data.list
      total.value = result.data.total
    } finally {
      loading.value = false
    }
  }
  const handleSizeChange = (val) => {
    pageInfo.value = {
      pageNum: 1,
      pageSize: val,
    }
    getData()
  }
  const handleCurrentChange = () => {
    getData()
  }
  const exportExcelBtn = async () => {
    let c = {
      startYear: ruleForm.value.date[0].split('-')[0] * 1,
      endYear: ruleForm.value.date[1].split('-')[0] * 1,
      startMonth: ruleForm.value.date[0].split('-')[1] * 1,
      endMonth: ruleForm.value.date[1].split('-')[1] * 1,
    }
    let res = await postSiteDetailExportQueryLike(
      { ...c },
      {
        loading: true,
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json; application/octet-stream',
        },
      },
    )
    let b = new Blob([res], { type: 'application/zip' }) //拿到文件流下载对象
    let url = window.URL.createObjectURL(b) //生成文件流下载链接
    let a = document.createElement('a') //创建一个a标签用来跳转
    a.href = url // a标签 href  赋值 链接
    a.download = '分成记录.zip' //设置下载文件的文件名和文件格式
    document.body.appendChild(a) //将标签DOM，放置页面
    a.click()
    window.URL.revokeObjectURL(url) //释放 url 对象内存
    document.body.removeChild(a) //移除标签节点
  }

  const fileList = ref([])
  //上传导入模板文件
  const uploadFile = async () => {
    const file = new FormData()
    file.append('file', fileList.value[0].raw)
    fileList.value = []
    let res = await postSiteDetailInputExcel(file, {
      loading: true,
    })
    let b = new Blob([res]) //拿到文件流下载对象
    let url = window.URL.createObjectURL(b) //生成文件流下载链接
    let a = document.createElement('a') //创建一个a标签用来跳转
    a.href = url // a标签 href  赋值 链接
    a.download = '上传结果.txt' //设置下载文件的文件名和文件格式
    document.body.appendChild(a) //将标签DOM，放置页面
    a.click()
    window.URL.revokeObjectURL(url) //释放 url 对象内存
    document.body.removeChild(a) //移除标签节点
    getData()
  }
  const beforeUpload = (file) => {
    const { name } = file
    //   文件类型限制
    const fileTypeFlag = /^.xlsx$/.test(name.substring(name.lastIndexOf('.')).toLowerCase())
    if (!fileTypeFlag) {
      ElMessage.warning('文件类型只能是.xlsx')
      return false
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
    .head {
      background-color: white;
      padding: 18px 18px 8px 18px;
      margin-bottom: 16px;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      box-shadow: 0 0 12px rgb(0 0 0 / 5%);
      .btn-item {
        margin-left: 12px;
      }
    }
    .tab {
      display: flex;
      flex-direction: column;
      background-color: white;
      padding: 20px;
      border-radius: 4px;
      box-shadow: 0 0 12px rgb(0 0 0 / 5%);
      flex: 1;
      .z-tab {
        position: relative;
        flex: 1;
        height: 100%;
        .table {
          position: absolute;
          height: 100%;
        }
      }
    }
    .foot {
      display: flex;
      justify-content: center;
      padding-top: 20px;
    }
  }
</style>
